package util;

import java.io.UnsupportedEncodingException;

public class EncodeConvert {
    //UTF-8->GB2312
    public static String utf8Togb2312(String str){

        StringBuffer sb = new StringBuffer();

        for ( int i=0; i<str.length(); i++) {

            char c = str.charAt(i);
            switch (c) {
                case '+' :
                    sb.append( ' ' );
                    break ;
                case '%' :
                    try {
                        sb.append(( char )Integer.parseInt (
                                str.substring(i+1,i+3),16));
                    }
                    catch (NumberFormatException e) {
                        throw new IllegalArgumentException();
                    }

                    i += 2;

                    break ;

                default :

                    sb.append(c);

                    break ;

            }

        }

        String result = sb.toString();
        String res= null;
        try {

            byte [] inputBytes = result.getBytes( "8859_1" );

            res= new String(inputBytes, "UTF-8" );

        }

        catch (Exception e){}

        return res;

    }
    public static String convertToGB2312(String string) {

        try {

            System.out.println(string);
            String utf8 = new String(string.getBytes("UTF-8"));
            System.out.println(utf8);
            String unicode = new String(utf8.getBytes(), "UTF-8");
            System.out.println(unicode);
            String gbk = new String(unicode.getBytes("GBK"));
            System.out.println(gbk);
            return gbk;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;

//
//        byte[] b = new byte[0];//编码
//        try {
//            b = string.getBytes("utf-8");
//            String sa = new String(b, "ISO-8859-1"); //gb2312
//            return sa;
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        return null;

//        String SB = null;
//        try {
//            StringBuffer sb = new StringBuffer();
//            try {
//                byte[] bytes = string.getBytes("GB2312");
//                for (byte b : bytes) {
//                    SB=new String(Integer.toHexString(b));
//                    System.out.println(SB);
//                    sb.append(SB);
//                }
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            return sb.toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
    }
}
